import json
import logging
from datetime import datetime
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)

class DataParser:
    """数据解析工具类"""
    
    @staticmethod
    def parse_coze_response(response_data: str) -> Optional[Dict[str, Any]]:
        """解析扣子API响应数据
        
        Args:
            response_data: 扣子API返回的JSON字符串
            
        Returns:
            解析后的数据字典，解析失败返回None
        """
        try:
            # 解析JSON字符串
            data = json.loads(response_data)
            
            # 获取data字段
            if 'data' in data:
                data_field = data['data']
                
                # 如果data字段是字符串，再次解析
                if isinstance(data_field, str):
                    data_field = json.loads(data_field)
                
                # 返回dy_data字段或整个data字段
                if isinstance(data_field, dict) and 'dy_data' in data_field:
                    return data_field['dy_data']
                else:
                    return data_field
            
            return data
            
        except (json.JSONDecodeError, Exception):
            return None
       
    

    
    @classmethod
    def parse_douyin_data(cls, response_data: str, source_url: str) -> Optional[Dict[str, Any]]:
        """解析抖音数据的完整流程
        
        Args:
            response_data: 扣子API响应数据
            source_url: 原始请求URL
            
        Returns:
            处理后的数据字典，失败返回None
        """
        try:
            # 解析JSON数据
            dy_data = cls.parse_coze_response(response_data)
            if not dy_data:
                return None
            
            # 处理时间戳
            release_time = None
            if dy_data.get('create_time'):
                try:
                    timestamp = int(dy_data['create_time'])
                    if timestamp > 1e10:  # 毫秒级时间戳
                        timestamp = timestamp / 1000
                    release_time = datetime.fromtimestamp(timestamp)
                except:
                    pass
            
            # 处理图片列表
            images = None
            if dy_data.get('images'):
                if isinstance(dy_data['images'], list):
                    valid_images = [str(img) for img in dy_data['images'] if img]
                    if valid_images:
                        images = ','.join(valid_images)
                elif isinstance(dy_data['images'], str):
                    images = dy_data['images']
            
            # 判断作品类型
            work_type = 'unknown'
            if dy_data.get('videoUrl'):
                work_type = 'video'
            elif images:
                work_type = 'image'
            
            # 构建结果数据
            result = {
                'platform_type': 'douyin',
                'platform_name': '抖音',
                'kol_name': str(dy_data.get('author', '')),
                'kol_platform_id': str(dy_data.get('sec_uid', '')),
                'title': str(dy_data.get('title', '')),
                'type': work_type,
                'images': images,
                'video': dy_data.get('videoUrl'),
                'cover': dy_data.get('cover'),
                'tags': str(dy_data.get('hashtagNames', '')),
                'release_time': release_time,
                'source_link': source_url,
                'comment_count': int(dy_data.get('comment_count', 0)),
                'collect_count': int(dy_data.get('collect_count', 0)),
                'like_count': int(dy_data.get('like_count', 0)),
                'share_count': int(dy_data.get('share_count', 0))
            }
            
            return result
            
        except Exception:
            return None